import {Component, OnInit} from '@angular/core';
import { Menu } from '../menu';
import {Router, ActivatedRoute} from "@angular/router";
import {MenusService} from "../menus.service";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {MsgResult} from "../../../../models/msg-result";
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import {MsgConstants} from "../../../../constants/constants";
import {TreeUtil} from "../../../../util/tree-util";
declare var $;

@Component({
  selector: 'app-menu-add',
  templateUrl: './menu-add.component.html'
})
export class MenuAddComponent implements OnInit {

  menu :Menu;

  menuForm: FormGroup;

  treeObj;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private treeUtil: TreeUtil,
    private pageSubject : PageSubject,
    private responseUtil : ResponseUtil,
    private dialogService : OneDialogService,
    private menusService :MenusService
  ) {
     this.initObject();
  }

  ngOnInit() {
    this.initMenuZTree();
    this.pushPage();
  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("菜单管理","添加",path);
  }


  /**
   * 构造表单
   */
  buildForm(): void {
    this.menuForm = this.fb.group({
      'pId': [this.menu.pId],
      'pName': [this.menu.pName],
      'id': [this.menu.id],
      'name': [this.menu.name, [
        Validators.required,
        Validators.maxLength(30)
      ]],
      'menuCode': [this.menu.menuCode, [
        Validators.required,
        Validators.pattern(/^[A-Za-z0-9]+$/)
      ]],
      'cssName': [this.menu.cssName, [
        Validators.pattern(/^[a-z0-9\-\s]*$/)
      ]],
      'url': [this.menu.url, [
        Validators.pattern(/^[^\u4e00-\u9fa5]{0,}$/)
      ]],
      'orderBy': [this.menu.orderBy, [
        Validators.required,
        Validators.maxLength(4),
        Validators.pattern(/^[\d]{0,}$/)
      ]],
      'remark': [this.menu.remark, [
        Validators.maxLength(30)
      ]],
      'type': [this.menu.isEnable, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isEnable': [this.menu.isEnable, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isDisplay': [this.menu.isDisplay, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isBlank': [this.menu.isDisplay, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isExistUrl': [this.menu.isDisplay, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isExternal': [this.menu.isDisplay, [
        Validators.required,
        Validators.maxLength(1)
      ]]
    });

    this.menuForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.menuForm) {
      return;
    }
    const form = this.menuForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'name': '',
    'pName': '',
    'menuCode': '',
    'cssName': '',
    'url': '',
    'orderBy': '',
    'remark': '',
    'isDisplay': '',
    'isEnable': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'name': {
      'required': '菜单名不能为空',
      'maxlength': '长度不能超过30',
    },
    'pName': {
      'maxlength': '长度不能超过30',
    },
    'menuCode': {
      'required': '菜单编码不能为空',
      'pattern': '只能由字母、数字组成'
    },
    'cssName': {
      'pattern': '只能由字母、数字、空格、中划线组成'
    },
    'url': {
      'pattern': '只能由字母、数字、短线组成'
    },
    'orderBy': {
      'required': '序列号不能为空',
      'pattern': '只能是数字' ,
      'maxlength': '长度不能超过4位'
    },
    'remark': {
      'maxlength': '长度不能超过30',
    }
  };

  /**
   * 保存菜单修改信息
   */
  onSubmit(){
    console.log(this.menuForm.value);
    this.menu = this.menuForm.value;
    if(this.menu.isExistUrl == "0"){
      this.menu.url = "";
    }
    this.menusService.insertMenu(this.menu).subscribe(
      result =>this.responseUtil.success(result,this.processMenuAddResult),
      message=>this.responseUtil.error(message)
    );
  }

  /**
   * 处理添加结果
   * @param result
   */
  private processMenuAddResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.successWithCancelBtn("添加成功，是否继续添加？", () => this.initObject(), () => this.cancelMenuAdd());
      //用于实时刷新添加中的菜单树
      this.initMenuZTree();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消添加菜单
   */
  cancelMenuAdd(){
    this.router.navigate(['..'],{relativeTo :this.route});
  }

  /**
   * 实例化对象
   */
  private initObject(){
    this.menu = new Menu("","","","","","","","","","0","0","0","0","0","0");
    this.buildForm();
  }

  /**
   * 初始化菜单树
   */
  initMenuZTree() {
    this.menusService.getMenus().subscribe(
      result => this.responseUtil.success(result, this.processMenuTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.initMenusTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  initMenusTree(menus) {
    //初始化菜单树
    let setting = {
      callback: {
        onClick: this.clickTree
      }
    };

    let zNodes =this.treeUtil.wrapToStandard(menus);
    console.log(zNodes);

    //把树放进页面
    this.treeObj = $.fn.zTree.init($("#menu_add_ZTree"), setting, zNodes);

  }
  clickTree = (event, treeId, treeNode) => {
    if(treeNode.id == this.menuForm.value.pId){
      let nodes = this.treeObj.getSelectedNodes();
      if (nodes.length>0) {
        this.treeObj.cancelSelectedNode(nodes[0]);
      }
      this.menu = this.menuForm.value;
      this.menu.pId = "";
      this.menu.pName = "";
      this.menuForm.patchValue(this.menu);
    }else{
      this.menu = this.menuForm.value;
      this.menu.pId = treeNode.id;
      this.menu.pName = treeNode.name;
      this.menuForm.patchValue(this.menu);
    }
  }
}
